// myAddress.js
const regeneratorRuntime = require('../../lib/runtime');
const Api = require('../../utils/api.js');
const wx = require('../../lib/wx');
const wxapp = require('../../lib/wxapp');
const Util = require('../../utils/util.js');

// 获取应用实例
const app = getApp();
Page({
  data: {
    showDetail: false,
    region: ['北京市', '东城区', '东华门街道'],
    userList: [],
    currentUser: {},
    province:[],
    city:[],
    area:[],
    default_country:0,
    pikerScenes:false,
    // piker滚动选中值
    regionInfo: ['北京市', '东城区', '东华门街道'],
    // 默认选择数组 0:第一个数组 ，这里是三列
    value: [0, 0, 0],
    regionId:[1,37,567],
    id:0,
    regionData : []
  },

  addNewAddress: wxapp.handler(function* addNewAddress(next){
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if(!token){
      wx.reLaunch({
        url,
      });
    }
    wx.setNavigationBarTitle({
      title: '地址详情',
    });
    this.setData({
      currentUser: {},
      showDetail: true,
    });

    yield next;
  }),

  bindRegionChange: wxapp.handler(function* bindRegionChange(next, e) {
      var that = this;
      var obj=[];
      var value = e.detail.value;
      var info = that.data.regionInfo;
      var regionId = [];
      
      // 省列表数据
      var getRegion = Api.getRegion();
      var provinceList = [];
      wx.request({
        url: getRegion,
        header: {
          'content-type': 'application/json'
        },
        method: 'GET',
        data: {
          pid: 0
        },
        complete: function (res) {
          for(var i=0;i<res.data.data.length;i++){
            provinceList.push(res.data.data[i]);
          }
          var provinceInfo = provinceList[value[0]];
          obj.push(provinceInfo['regname']);
          regionId.push(provinceInfo['regid']);
          that.setData({ regionInfo: obj, regionId: regionId});
          var cityList = [];
          wx.request({
            url: getRegion,
            header: {
              'content-type': 'application/json'
            },
            method: 'GET',
            data: {
              pid: provinceInfo['regid']
            },
            complete: function (res) {
              for (var i=0; i < res.data.data.length; i++) {
                cityList.push(res.data.data[i]);
              }

              var cityInfo = cityList[value[1]];
              obj.push(cityInfo['regname']);
              regionId.push(cityInfo['regid']);
              that.setData({ city: cityList, regionInfo: obj, regionId: regionId });
              var areaList = [];
              wx.request({
                url: getRegion,
                header: {
                  'content-type': 'application/json'
                },
                method: 'GET',
                data: {
                  pid: cityInfo['regid']
                },
                complete: function (res) {
                  for (var i = 0; i < res.data.data.length; i++) {
                    areaList.push(res.data.data[i]);
                  }
                  var areaInfo = areaList[value[2]];
                  obj.push(areaInfo['regname']);
                  regionId.push(areaInfo['regid']);
                  that.setData({ area: areaList, regionInfo: obj, regionId: regionId});
                }
              });
            }
          });
        }
      });
    


     yield next;
  }),

  pikerScenes:function(){
    var that = this;
    var pikerScenes = that.data.pikerScenes;
    var p = pikerScenes == true?false:true;
    that.setData({
      pikerScenes:p
    })
  },

  // 点击了piker 的确认
  pikerConfirm:function(){
    var that =this
    that.setData({
      region: that.data.regionInfo
    })
    // 隐藏piker
    that.pikerScenes()
  },
  // 点击了piker 的取消
  pikerCancel:function(){
    var that =this;
    // 隐藏piker
    that.pikerScenes();
  },

  submitAddress: wxapp.handler(function* submitAddress(next, e){
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if(!token){
      wx.reLaunch({
        url,
      });
    }
    const submitValue = e.detail.value; console.log(submitValue);
    const addressee = submitValue.addressee;
    const phone = submitValue.phone;
    const mobileRule = new RegExp(/^1[3|4|5|7|8]\d{9}$/);
    const selected = false;
    const area = this.data.regionInfo;
    const address = submitValue.address;
    const addressText = area[0] + '-' +area[1] + '-' + area[2] + ' ' + address;
    const regionId = this.data.regionId; console.log(regionId);
    if(addressee === ''){
      wx.showToast({
        title: '请填写收件人',
        image: '../../images/warn.png',
        duration: 2000,
      });
      return;
    } else if(phone === ''){
      wx.showToast({
        title: '请填写手机号码',
        image: '../../images/warn.png',
        duration: 2000,
      });
      return;
    } else if (!mobileRule.test(phone)) {
      wx.showToast({
        title: '手机格式不正确',
        image: '../../images/error.png',
        duration: 2000,
      });
      return;
    } else if(address === ''){
      wx.showToast({
        title: '请填写详细地址',
        image: '../../images/warn.png',
        duration: 2000,
      });
      return;
    }
    wx.setNavigationBarTitle({
      title: '地址选择',
    });
    var userList = this.data.userList;
    if(!userList){
      userList = [];
    }
    let userInfo = {
      addressee,
      phone,
      address,
      area,
      addressText,
      selected,
      regionId,
      id:this.data.id
    };

    const that = this;
    const getAddressEdit = Api.getAddressEdit();
    let postData = JSON.stringify(userInfo);
    
    // 购物车
    wx.request({
      url: getAddressEdit,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: {
        info: postData,
        token:token,
        id:that.data.id
      },
      complete: function (res) {
        var userInfo = {
          addressee,
          phone,
          address,
          area,
          addressText,
          selected,
          regionId,
          id:res.data.data
        };
        if(that.data.id){
          for(var i=0;i<userList.length;i++){
            if(that.data.id == userList[i]['id']){
              userList.splice(i,1,userInfo);
            }
          }
        }else{
          userList.push(userInfo);
        }
        that.setData({
          userList: userList,
          showDetail: false,
        });
        console.log(that.data.userList);
      }
    });
    
    

  }),

  selectAddress: wxapp.handler(function* selectAddress(next, e){
    const pageData = this.data;
    let userList = pageData.userList;
    console.log(userList);
    const currentIndex = e.currentTarget.dataset.index;
    if(userList[currentIndex].selected){
      userList[currentIndex].selected = false;
    } else{
      userList[currentIndex].selected = true;
    }
    this.setData({
      userList,
    });

    wx.setStorage({
      key: "choseAddress",
      data: userList[currentIndex]
    })

    if(userList[currentIndex].selected){
      wx.navigateBack({
        delta: 1,
      });
    }

    yield next;
  }),

  editAddress: wxapp.handler(function* editAddress(next, e) {
    const currentIndex = e.currentTarget.dataset.index;
    const pageData = this.data;
    let userList = pageData.userList;
    const currentUser = userList[currentIndex];
    this.setData({
      currentUser,
      showDetail: true,
      region:currentUser['area'],
      id:currentUser['id']
    });

    yield next;
  }),

  deleteAddress: wxapp.handler(function* deleteAddress(next,e) {
    console.log(e);
    const authTokenKey = Util.authTokenKey();
    var token = wx.getStorageSync(authTokenKey);
    var getUserAddressDelete = Api.getUserAddressDelete();
    var that = this;

    // 购物车
    wx.request({
      url: getUserAddressDelete,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: {
        token: token,
        id: e.currentTarget.dataset.id
      },
      complete: function (res) {
        if (res.data.status != 1) {
          wx.showModal({
            title: res.data.msg
          })
        } else {
          let userList = that.data.userList;
          userList.splice(e.currentTarget.dataset.index, 1);
          that.setData({
            userList: userList
          });
        }
      }
    });

    yield next;
  }),
  

  onShow: wxapp.handler(function* onShow(next) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if(!token){
      wx.reLaunch({
        url,
      });
      return ;
    }
    var that = this;

    
    
    
    var getRegion = Api.getRegion();
    wx.request({
      url: getRegion,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {
        pid:0
      },
      complete: function (res) {
        var provinceList = [];
        for(var i=0;i<res.data.data.length;i++){
          provinceList.push(res.data.data[i]);
        }
        that.setData({
          province:provinceList
        });
        // console.log(that.data.province);
      }
    });
    wx.request({
      url: getRegion,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {
        pid:1
      },
      complete: function (res) {
        var cityList = [];
        for (var i = 0; i < res.data.data.length; i++) {
          cityList.push(res.data.data[i]);
        }
        that.setData({
          city: cityList
        });
      }
    });
    wx.request({
      url: getRegion,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {
        pid: 37
      },
      complete: function (res) {
        var areaList = [];
        for (var i = 0; i < res.data.data.length; i++) {
          areaList.push(res.data.data[i]);
        }
        that.setData({
          area: areaList
        });
      }
    });


    var getUserAddressList = Api.getUserAddressList();
    // console.log(getAddressEdit);
    // 购物车
      wx.request({
      url: getUserAddressList,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {
        token:token
      },
      complete: function (res) {
        that.setData({
          userList:res.data.data
        });
      }
    });

    yield next;
  }),

});
